<?php

namespace App\Http\Controllers\Entity\Column;

use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\Column\ColumnTypeRequest;
use App\Models\Application\Pagetpl;
use App\Models\Application\Paneltpl;
use App\Models\Common\EntityData\Channel\Ogroup;
use App\Models\Common\EntityData\Channel\Sp;
use App\Models\Entity\Column\ColumnType;
use App\Repositories\Entity\Column\ColumnTypeRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Response;

class ColumnTypeController extends Controller
{
    use ModelForm;

    /** @var  ColumnTypeRepository */
    private $columnTypeRepository;

    public function __construct(ColumnTypeRepository $columnTypeRepo)
    {
        $this->columnTypeRepository = $columnTypeRepo;
    }

    /**
     * Display a listing of the ColumnType.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.column.column_types.index_header'));
            $content->description(__('entity.column.column_types.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new ColumnType.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.column.column_types.create_header'));
            $content->description(__('entity.column.column_types.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created ColumnType in storage.
     *
     * @param ColumnTypeRequest $request
     *
     * @return Response
     */
    public function store(ColumnTypeRequest $request)
    {
        $input = $request->all();

        $columnType = $this->columnTypeRepository->create($input);

        Flash::success(__('entity.column.column_types.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.column.column_types.index'));

    }

    /**
     * Display the specified ColumnType.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $columnType = $this->columnTypeRepository->findWithoutFail($id);

        if (empty($columnType)) {
            Flash::error(__('entity.column.column_types.not_found'));

            return redirect(route('entity.column.column_types.index'));
        }

        return view('entity.column.column_types.show')->with('columnType', $columnType);

    }

    /**
     * Show the form for editing the specified ColumnType.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $columnType = $this->columnTypeRepository->findWithoutFail($id);

        if (empty($columnType)) {
            Flash::error(__('entity.column.column_types.not_found'));

            return redirect(route('entity.column.column_types.index'));
        }
        return Admin::content(function (Content $content) use ($id, $columnType) {

            $content->header(__('entity.column.column_types.edit_header'));
            $content->description(__('entity.column.column_types.edit_description'));

            $content->body($this->form()->edit($id));
            $range = empty($columnType->range) ? 0 :$columnType->range;
            $content->row(view('entity.column.column-type.edit', ['range' => $range, 'tpl_id' => $columnType->tpl_id]));
        });
    }

    /**
     * Update the specified ColumnType in storage.
     *
     * @param  int              $id
     * @param ColumnTypeRequest $request
     *
     * @return Response
     */
    public function update($id, ColumnTypeRequest $request)
    {
        $columnType = $this->columnTypeRepository->findWithoutFail($id);

        if (empty($columnType)) {
            Flash::error(__('entity.column.column_types.not_found'));

            return redirect(route('entity.column.column_types.index'));
        }
        $input = $request->all();

        $columnType = $this->columnTypeRepository->update($input, $id);

        Flash::success(__('entity.column.column_types.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.column.column_types.index'));
    }

    /**
     * Remove the specified ColumnType from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->columnTypeRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('entity.column.column_types.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $columnType = $this->columnTypeRepository->findWithoutFail($id);

        if (empty($columnType)) {
            Flash::error(__('entity.column.column_types.not_found'));

            return redirect(route('entity.column.column_types.index'));
        }

        if ($flag = $this->columnTypeRepository->delete($id)) {

            return response()->json(['message' => __('entity.column.column_types.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(ColumnType::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '栏目名称');
            $form->text('title', '栏目显示名');
            // $form->number('pid', '父栏目类型');
            $columnTypes = ColumnType::get(['id', 'pid', 'title'])->toArray();
            $columnTypes = array_merge([['id' => 0, 'pid' => 0, 'title' => '选择']], $columnTypes);
            $form->ztree('pid', '上级栏目类型')
                ->zTreeConfig(["map" => ["id" => "id", "title" => 'name', 'pid' => 'pId'], "type" => "radio", "open" => true])
                ->options($columnTypes);

            $form->select('range', 'range')->options(array(
                '0' => '选择',
                '1' => 'area',
                '2' => 'page',
                '3' => 'app',
                '4' => 'list',
            ))->load('tpl_id', route('entity.column.collists.tpls'), 'id', 'title')->help('选中range时模板不能为空');
            $paneltpls = Paneltpl::pluck('title', 'id')->toArray();
            $form->select('tpl_id', '模板')->options(array_merge(['0' => '选择'], $paneltpls));
            $sps = Sp::pluck('name', 'id');
            $form->select('sp_id', 'SP')->options($sps);
            $ogroups = Ogroup::pluck('name', 'id');
            $form->select('ogroup_id', '渠道')->options($ogroups);
            $form->textarea('datasrc', '数据源');
            $form->textarea('tags', 'tags')->help('必填');
            $form->textarea('description', '描述');

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(ColumnType::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('entity.column.column_types.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('entity.column.column_types.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('entity.column.column_types.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('entity.column.column_types.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('entity.column.column_types.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('entity.column.column_types.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('entity.column.column_types.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.column.column_types.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('entity.column.column_types.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.column.column_types.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '栏目名称')->sortable();
            $grid->column('title', '栏目显示名')->sortable();
            $grid->column('pid', '上级栏目类型')->display(function ($val) {
                $columnTypeName = ColumnType::where('id', $val)->value('title');
                return $columnTypeName ? $columnTypeName : '';
            })->sortable();
            $grid->column('range', 'range')->display(function ($val) {
                switch ($val) {
                    case '1':
                        return '<span class="badge bg-green">area</span>';
                        break;
                    case '2':
                        return '<span class="badge bg-green">page</span>';
                        break;
                    case '3':
                        return '<span class="badge bg-green">app</span>';
                        break;
                    case '4':
                        return '<span class="badge bg-green">list</span>';
                        break;
                    default:
                        return '';
                        break;
                }
            });
            $grid->column('tpl_id', '模板')->display(function ($val) {
                $returnName = '';
                switch ($this->range) {
                    case '1':
                        $returnName = Paneltpl::where(['id' => $val])->value('title');
                        break;
                    default:
                        $returnName = Pagetpl::where(['id' => $val])->value('title');
                        break;
                }
                return empty($returnName) ? '' : $returnName;
            });
            // $grid->column('sp.name', 'SP')->sortable();
            $grid->column('ogroup.name', '渠道')->sortable();
            $grid->column('datasrc', '数据源')->sortable();
            $grid->column('tags', 'tags')->sortable();
            $grid->column('description', '描述')->sortable()->display(function ($val) {
                if (!empty($val)) {
                    return Str::limit($val, 20);
                }
                return '';
            });

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '栏目名称');

            });
        });
    }
}
